package net.jforum.view.forum;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.jforum.Command;
import net.jforum.JForumExecutionContext;
import net.jforum.entities.Forum;
import net.jforum.entities.Topic;
import net.jforum.repository.ForumRepository;
import net.jforum.repository.TopicRepository;
import net.jforum.util.I18n;
import net.jforum.util.SEOUtil;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;
import net.jforum.util.preferences.TemplateKeys;
import net.jforum.view.forum.common.TopicsCommon;
import net.jforum.view.forum.common.ViewCommon;

/**
 * @ author  张洋 jackson.zhang@ericsson.com
 * @ version 创建时间 ：Aug 9, 2010  12:21:02 AM
 * @ description : 
 */
public class KuTopicsAction extends Command{

	private List forums;

	public void list()
	{   
		int start = ViewCommon.getStartPage();
	 	int topicsPerPage = SystemGlobals.getIntValue(ConfigKeys.TOPICS_PER_PAGE);
		int totalTopics =TopicRepository.getKuTopicsCount() ;
        int postPerPage=SystemGlobals.getIntValue(ConfigKeys.POSTS_PER_PAGE);
		ViewCommon.contextToPagination(start, totalTopics, topicsPerPage);
		this.context.put("postsPerPage", new Integer(postPerPage));
//		this.context.put("recordsPerPage", new Integer(topicsPerPage));
		this.setTemplateName(TemplateKeys.KUTOPICS_LIST);
		
	//	this.context.put("postsPerPage", new Integer(topicsPerPage));
		this.context.put("topics", this.topics(start));
		this.context.put("forums", this.forums);
		this.context.put("pageTitle", SEOUtil.forumShowSEO(I18n.getMessage("ForumBase.kuTie")));
        this.context.put("module", "allTopics");
		TopicsCommon.topicListingBase();
		this.request.setAttribute("template", null);
	}
	
	private List topics(int start)
	{
		int topicPerPage = SystemGlobals.getIntValue(ConfigKeys.TOPICS_PER_PAGE);
		List topics = TopicRepository.getKuTopicsByLimit(start,topicPerPage);
		
		this.forums = new ArrayList(topicPerPage);

		for (Iterator iter = topics.iterator(); iter.hasNext(); ) {
			Topic t = (Topic)iter.next();
			
			if (TopicsCommon.isTopicAccessible(t.getForumId())) {
				Forum f = ForumRepository.getForum(t.getForumId());
				forums.add(f);
			}
			else {
				iter.remove();
			}
		}
		
		JForumExecutionContext.getRequest().removeAttribute("template");
		
		return TopicsCommon.prepareTopics(topics);
	}
}
